package View;

import java.awt.Component;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Vector;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreePath;

import DTO.Field;
import DTO.Table;
import Listener.ButtonAddListener;
import Listener.ButtonViewCliListener;
import Listener.TreeListener;
import Main.Database;
import XML.XMLHelper;


public class ServerScreen {

	static public JFrame frame;
	//static public JTable table;
	public static SpringLayout springLayout;
	public static JTabbedPane tabbedPane;
	private JToolBar toolBar;
	public static JTree tree;
	public static DefaultMutableTreeNode top; // root node <tree>
	public static DefaultTreeModel treeModel;
	public static TreePath selPath;
	static JMenu mnConnect;
	static JMenuItem mntmDelete;
	static JMenuItem mntmOpen;
	
	public static Database database;

	private static int rowSelected = -1; // temp
	public static Vector tableOpened; //luu tam ~ table nao dang duoc mo

	private TreeListener treeListener;
	private ButtonAddListener addListener;
	private ButtonViewCliListener viewListener;
	private ClientManager manager;
	
	private static About about;
	public static ClientListScreen cliListScreen;

	/**
	 * Create the application.
	 */
	public ServerScreen() {
		treeListener = new TreeListener();
		addListener = new ButtonAddListener();
		viewListener = new ButtonViewCliListener();
		tableOpened = new Vector();
		
		about = new About();
		cliListScreen = new ClientListScreen();
		
		manager = new ClientManager();

		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		try {
			UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedLookAndFeelException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		frame = new JFrame();
		frame.setIconImage(Toolkit.getDefaultToolkit().getImage(
				"res\\database-icon.png"));
		frame.setTitle("Server");
		frame.setBounds(100, 100, 804, 456);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		createMenu();

		springLayout = new SpringLayout();
		frame.getContentPane().setLayout(springLayout);

		createTabArea();

		createToolbar();

		createTree();
		
		manager.createXMLFile("ClientList");

	}

	private void createMenu() {
		JMenuBar menuBar = new JMenuBar();
		frame.setJMenuBar(menuBar);

		JMenu mnFile = new JMenu("File");
		menuBar.add(mnFile);

		JMenuItem mntmExit = new JMenuItem("Exit");
		mntmExit.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				System.exit(0);
			}
			
		});
		mnFile.add(mntmExit);

		mnConnect = new JMenu("Connect");
		menuBar.add(mnConnect);

		mntmOpen = new JMenuItem("Open");
		mntmOpen.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				Server server = new Server();
				mnConnect.setVisible(false);
			}

		});
		mnConnect.add(mntmOpen);

		JMenu mnHelp = new JMenu("Help");
		menuBar.add(mnHelp);
		
		JMenuItem mntmAbout = new JMenuItem("About");
		mntmAbout.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				about.frmAbout.setVisible(true);
			}
			
		});
		mnHelp.add(mntmAbout);
	}

	private void createTabArea() {
		tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		springLayout.putConstraint(SpringLayout.NORTH, tabbedPane, 0,
				SpringLayout.NORTH, frame.getContentPane());
		springLayout.putConstraint(SpringLayout.SOUTH, tabbedPane, 0,
				SpringLayout.SOUTH, frame.getContentPane());
		springLayout.putConstraint(SpringLayout.EAST, tabbedPane, 0,
				SpringLayout.EAST, frame.getContentPane());
		tabbedPane.setBorder(new CompoundBorder());
		frame.getContentPane().add(tabbedPane);
	}


	private void createToolbar() {
		toolBar = new JToolBar();
		springLayout.putConstraint(SpringLayout.WEST, tabbedPane, 6,
				SpringLayout.EAST, toolBar);

		springLayout.putConstraint(SpringLayout.WEST, toolBar, 0,
				SpringLayout.WEST, frame.getContentPane());
		springLayout.putConstraint(SpringLayout.SOUTH, toolBar, 50,
				SpringLayout.NORTH, frame.getContentPane());
		springLayout.putConstraint(SpringLayout.NORTH, toolBar, 0,
				SpringLayout.NORTH, frame.getContentPane());
		springLayout.putConstraint(SpringLayout.EAST, toolBar, 200,
				SpringLayout.WEST, frame.getContentPane());

		frame.getContentPane().add(toolBar);

		JButton btnAdd = new JButton("");
		btnAdd.setToolTipText("Add Table");
		btnAdd.setIcon(new ImageIcon("res\\add-icon.png"));
		btnAdd.addActionListener(addListener);
		toolBar.add(btnAdd);

		JButton btnViewClients = new JButton("");
		btnViewClients.setToolTipText("View Clients");
		btnViewClients.setIcon(new ImageIcon("res\\view-list-icon.png"));
		btnViewClients.addActionListener(viewListener);
		toolBar.add(btnViewClients);
	}

	private void createTree() {
		database = Database.createDatabase("TruongHoc");
		String databaseName = database.getName();
		
		top = new DefaultMutableTreeNode(databaseName);	
		createNodes(top, database);
		treeModel = new DefaultTreeModel(top);
		tree = new JTree(treeModel);
		
		DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
		renderer.setOpenIcon(new ImageIcon("res\\table-icon.png"));
		renderer.setClosedIcon(new ImageIcon("res\\table-icon.png"));
		renderer.setLeafIcon(new ImageIcon("res\\column-icon.png"));

		tree.setCellRenderer(renderer);
		tree.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
		tree.addMouseListener(treeListener);

		JScrollPane scrollPaneOfList = new JScrollPane(tree);

		JPopupMenu popupMenu = new JPopupMenu();
		//addPopup(tree, popupMenu);

		mntmDelete = new JMenuItem("Delete");

		mntmDelete.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				if (selPath != null) {
					MutableTreeNode node = (MutableTreeNode) selPath
							.getLastPathComponent();
					int option = JOptionPane.showConfirmDialog(frame,
							"Are you sure to delete " + node, "Delete Table",
							JOptionPane.OK_CANCEL_OPTION);
					if (option == JOptionPane.OK_OPTION) {
						deleteTreeNode(selPath);
					} else {
						JOptionPane.showMessageDialog(frame,
								"Delete table cancel!!!");
					}
				}
			}

		});
		popupMenu.add(mntmDelete);

		JMenuItem mntmRename = new JMenuItem("Rename");
		popupMenu.add(mntmRename);

		springLayout.putConstraint(SpringLayout.NORTH, scrollPaneOfList, 6,
				SpringLayout.SOUTH, toolBar);
		springLayout.putConstraint(SpringLayout.WEST, scrollPaneOfList, 10,
				SpringLayout.WEST, toolBar);
		springLayout.putConstraint(SpringLayout.SOUTH, scrollPaneOfList, 0,
				SpringLayout.SOUTH, tabbedPane);
		springLayout.putConstraint(SpringLayout.EAST, scrollPaneOfList, -6,
				SpringLayout.WEST, tabbedPane);
		frame.getContentPane().add(scrollPaneOfList);
	}
	
	static public void reloadTree(){
		top.removeAllChildren();
			
		if(database != null){
			database.load();
			ArrayList<Table> tableDb = database.getTableArrayList();
			
			DefaultMutableTreeNode[] tables = new DefaultMutableTreeNode[tableDb.size()];
			DefaultMutableTreeNode column = null;

			for (int i = 0; i < tables.length; i++) {
				tables[i] = new DefaultMutableTreeNode(tableDb.get(i).get_Name());
				Vector<Field> fields = tableDb.get(i).get_Fields();
				for (int j = 0; j < fields.size(); j++) {
					column = new DefaultMutableTreeNode(fields.get(j).get_Name());
					tables[i].add(column);
				}
				top.add(tables[i]);
			}
		}
		
		treeModel.reload();
	}

	private void createNodes(DefaultMutableTreeNode top, Database database) {
		if(database != null){
			database.load();
			ArrayList<Table> tableDb = database.getTableArrayList();
			
			DefaultMutableTreeNode[] tables = new DefaultMutableTreeNode[tableDb.size()];
			DefaultMutableTreeNode column = null;

			for (int i = 0; i < tables.length; i++) {
				tables[i] = new DefaultMutableTreeNode(tableDb.get(i).get_Name());
				Vector<Field> fields = tableDb.get(i).get_Fields();
				for (int j = 0; j < fields.size(); j++) {
					column = new DefaultMutableTreeNode(fields.get(j).get_Name());
					tables[i].add(column);
				}
				top.add(tables[i]);
			}
		}/*else{
		
			DefaultMutableTreeNode[] tables = new DefaultMutableTreeNode[5];
			DefaultMutableTreeNode column = null;
			
			for (int i = 0; i < tables.length; i++) {
				tables[i] = new DefaultMutableTreeNode("Table" + i);
				for (int j = 0; j < 5; j++) {
					column = new DefaultMutableTreeNode("Column" + j);
					tables[i].add(column);
				}
				top.add(tables[i]);
			}
		}*/
	}

	private static void addPopup(Component component, final JPopupMenu popup) {
		component.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}

			public void mouseReleased(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}

			private void showMenu(MouseEvent e) {
				popup.show(e.getComponent(), e.getX(), e.getY());
			}
		});
	}


	/*
	 * delete tree node
	 */

	private boolean deleteTreeNode(TreePath path) {
				
		System.out.println(path);
		if (path != null) {
			MutableTreeNode node = (MutableTreeNode) path
					.getLastPathComponent();
			System.out.println(top.getIndex(node));
			if (top == node) {
				JOptionPane.showMessageDialog(frame,
						"Can not delete this database!!!");
				return false;
			}
			for (int i = 0; i < top.getChildCount(); i++) {
				if (node == top.getChildAt(i)) {
					JOptionPane.showMessageDialog(frame,
							"Delete table " + top.getChildAt(i)
									+ " complete!!!");
					treeModel.removeNodeFromParent(node);
					return true;
				} else {
					for (int j = 0; j < top.getChildAt(i).getChildCount(); j++) {
						if (node == top.getChildAt(i).getChildAt(j)) {
							JOptionPane.showMessageDialog(frame,
									"Delete column "
											+ top.getChildAt(i).getChildAt(j)
											+ " complete!!!");
							treeModel.removeNodeFromParent(node);
							return true;
						}
					}
				}
			}
		}
		JOptionPane.showMessageDialog(frame, "Delete table fail!!!");
		return false;
	}
}
